const fs = require('fs-extra')
const path = require('path')
const UefileModel = require('../models/uefileModel')
const Cluster = require('../models/clusterModel')
const { get } = require('../utils/request')
const download = async (ctx, fileName) => {
  try {
    const filePath = path.resolve(__dirname, `../uefile/${fileName}`)
    const stats = fs.statSync(filePath) // 同步获取文件信息
    ctx.response.set('Content-Type', 'application/octet-stream')
    ctx.response.set(
      'Content-Disposition',
      `attachment; filename="${encodeURIComponent(fileName)}"`
    )
    ctx.response.set('Content-Length', stats.size) // 设置文件的大小
    const fileStream = fs.createReadStream(filePath)
    ctx.response.body = fileStream // 直接将可读流分配给响应体
  } catch (err) {
    throw new HttpError(err.message, 400)
  }
}
const addsyncFile = async data => {
  try {
    const instance = new UefileModel(data)
    await instance.save()
    return instance
  } catch (err) {
    throw new HttpError(err.message, 400)
  }
}

const updatesyncFile = async data => {
  try {
    await UefileModel.findByIdAndUpdate(data.id, data, {
      new: true
    })
  } catch (err) {
    throw new HttpError(err.message, 400)
  }
}

const getsyncFile = async (pageSize, pageNo, clusterId) => {
  try {
    const query = {}
    // 设置默认的分页参数
    pageNo = parseInt(pageNo) || 1
    pageSize = parseInt(pageSize) || 10
    const skip = (pageNo - 1) * pageSize
    if (clusterId) {
      query.clusterId = new RegExp(clusterId, 'i') // 用于模糊搜索的正则表达式
    }
    // 计算总记录数
    const total = await UefileModel.countDocuments(query)
    // 获得分页数据
    let records
    if (pageSize == -1) {
      records = await UefileModel.find(query).sort({ createdAt: -1 }).exec()
    } else {
      records = await UefileModel.find(query)
        .sort({ createdAt: -1 })
        .skip(skip)
        .limit(pageSize)
        .exec()
    }
    return { records, total }
  } catch (err) {
    throw new HttpError('查询错误！', 400)
  }
}

const clustersyncFile = async () => {
  try {
    const clusters = await Cluster.find({}).exec() // 获取所有数据
    const requests = []
    for (let i = 0, len = clusters.length; i < len; i++) {
      const url = `${clusters[i].protocol}://${clusters[i].host}:${clusters[i].port}/cluster/clustersyncFile`
      requests.push(get(url, { clusterId: clusters[i]._id }))
    }
    await Promise.all(requests)
  } catch (err) {
    throw new HttpError(err.message, 400)
  }
}
const deletesyncFile = async ids => {
  console.log('deletesyncFile', ids)
  try {
    // 删除数据库记录
    await UefileModel.deleteMany({ _id: { $in: ids } })
  } catch (err) {
    throw new HttpError(err.message, 400)
  }
}
module.exports = {
  download,
  addsyncFile,
  updatesyncFile,
  getsyncFile,
  clustersyncFile,
  deletesyncFile
}
